#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#
# 文件名称 : getNTPtime.py
# 文件描述 : 使用ntplib强制调整windows时间，只适合windows系统
# 编写人员 : HHL
# 修改人员 :
# 编修描述 : V0.01，时间2019.07.02
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#
__version__  = '0.01'
__status__   = 'beta'
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#


import os
import sys
import time
import ntplib
import ctypes
import platform

# 判断获取权限
def running_as_admin(fun):

    if ctypes.windll.shell32.IsUserAnAdmin():
        pass
    else:
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)

    fun()

# 获取并设置系统时间
def get_NTP_time():

    # import pdb; pdb.set_trace()

    c = ntplib.NTPClient()

    while True:

        try:
            response = c.request('pool.ntp.org')
            ts = response.tx_time
            _date = time.strftime('%Y-%m-%d',time.localtime(ts))
            _time = time.strftime('%X',time.localtime(ts))

            os.system('date {} && time {}'.format(_date,_time))

            return

        except:
            time.sleep(6)

if __name__ == '__main__':

    if 'Windows' == platform.system():

        # 隐藏dos窗口
        whnd = ctypes.windll.kernel32.GetConsoleWindow()
        if whnd != 0:
            ctypes.windll.user32.ShowWindow(whnd, 0)
            ctypes.windll.kernel32.CloseHandle(whnd)

        running_as_admin(get_NTP_time())

    else:
        print("worked under windows only")
